package com.yrot.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yrot.admin.dto.RelatedStaff;
import com.yrot.admin.dto.TrainInfo;
import com.yrot.admin.entity.SysQuestionBank;
import com.yrot.admin.entity.SysTrain;
import com.yrot.admin.form.ResultAccuracyJson;
import com.yrot.admin.form.TrainValid;
import com.yrot.admin.service.ISysResultService;
import com.yrot.admin.service.ISysTrainService;
import com.yrot.common.annotation.SysLog;
import com.yrot.common.result.R;
import com.yrot.common.result.Result;
import com.yrot.common.result.ResultUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hemin
 * @since 2019-04-02
 */
@RestController
@RequestMapping("/admin/train")
public class SysTrainController extends BaseController{

    @Autowired
    ISysTrainService trainService;

    @Autowired
    ISysResultService resultService;


    @GetMapping("/trains")
    public Result trains(int page,int limit,
                         @RequestParam(value = "trainName",required = false)String trainName,
                         @RequestParam(value = "trainStatus",required = false)Integer trainStatus){
        QueryWrapper<SysTrain> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(trainName)){
            queryWrapper.like("train_content",trainName);
        }
        if(trainStatus!=null){
            queryWrapper.eq("train_status",trainStatus);
        }
        queryWrapper.eq("expert_id",sysExpert().getExpertId());
        queryWrapper.orderByDesc("train_id");
        Page<SysTrain> pages = new Page<>(page, limit);
        IPage<SysTrain> trainPages = trainService.page(pages,queryWrapper);
        List<SysTrain> records = trainPages.getRecords();
        ArrayList<ResultAccuracyJson> accuracyJsons = new ArrayList<>();
        records.forEach(record->{
            Integer trainId = record.getTrainId();
            ResultAccuracyJson accuracy = resultService.findAccuracy(trainId);
            BeanUtils.copyProperties(record,accuracy);
            accuracyJsons.add(accuracy);
        });
        return ResultUtils.success(trainPages.getTotal(), accuracyJsons);
    }

    @PostMapping("/train")
    @SysLog("发布培训")
    public R saveTrain(@Valid TrainValid trainValid, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return R.error(bindingResult.getFieldError().getDefaultMessage());
        }
        SysTrain sysTrain = new SysTrain();
        BeanUtils.copyProperties(trainValid,sysTrain);
        sysTrain.setExpertId(sysExpert().getExpertId());
        return trainService.saveTrain(sysTrain);
    }

    @DeleteMapping("/train/{id}")
    public void deleteTrain(@PathVariable("id")Integer id){
        trainService.removeById(id);
    }

    @PutMapping("/train")
    @SysLog("编辑培训信息")
    public R updateTrain(@Valid TrainValid trainValid, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return R.error(bindingResult.getFieldError().getDefaultMessage());
        }
        SysTrain sysTrain = new SysTrain();
        BeanUtils.copyProperties(trainValid,sysTrain);
        if(trainService.saveOrUpdate(sysTrain)){
            return R.ok();
        }else{
            return R.error("修改失败");
        }
    }

    /**
     * 查询该专家最新的培训
     * @return 培训信息
     */
    @GetMapping("/now")
    public R getTrainByNow(){
        QueryWrapper<SysTrain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("expert_id",sysExpert().getExpertId());
        queryWrapper.orderByDesc("train_id");
        List<SysTrain> list = trainService.list(queryWrapper);
        if(list.isEmpty()){
            return R.error();
        }
        return R.ok(list.get(0));
    }

    /**
     * 正确率图表数据
     * @return 当前专家的正确率图表数据
     */
    @GetMapping("/chart")
    public R getTrain(){
        return trainService.findAccuracyByExpertId(sysExpert().getExpertId());
    }


    /**
     * @return 考试是否创建成功
     */
    @PostMapping(path = "/train/createExam")
    public R createExam(@RequestBody TrainInfo trainInfo){
        R result = trainService.creatExamAndPeople(trainInfo);
        return result;
    }
}
